<?php
namespace app\task\model;
use app\common\model\Order as OrderModel;
use app\common\model\User as UserModel;
use app\common\model\Setting as SettingModel;
use app\common\model\Printer as PrinterModel;
use app\common\model\Wxapp as WxappModel;
use think\Cache;
use think\Db;

/**
 * 订单模型
 */
class Order extends OrderModel
{
    /**
     * 待支付订单详情
     */
    public function payDetail($order_no)
    {
        return self::get(['order_no' => $order_no, 'pay_status' => 10], ['goods','shop','table']);
    }

    /**
     * 更新付款状态
     */
    public function updatePayStatus($transaction_id)
    {
		
		if($this['pay_status']['value']==20){
			//避免重复回调
			return true;
		}
		//订单排序号
		if($row_no = Cache::get('order_row_no_'.$this['wxapp_id'].'_'.$this['shop_id'])){
			if($row_no<100){
				$row_no = $row_no+1;
			}else{
				$row_no=1;
			}	
		}else{
			$row_no = 1;
		}
		Cache::set('order_row_no_'.$this['wxapp_id'].'_'.$this['shop_id'], $row_no);
        // 开启事务
        Db::startTrans();
        try {
			// 更新商品库存、销量
			$GoodsModel = new Goods;
			$GoodsModel->updateStockSales($this['goods']);
			//更新用户信息
			$user = UserModel::detail($this['user_id']);
			$user->pay = ['inc', $this['pay_price']];//增加消费金额
			$user->score = ['inc', $this['pay_price']*100];//增加积分
			$user->save();
			
			// 更新订单状态
			$this->save([
				'row_no' => $row_no,
				'pay_status' => 20,
				'pay_time' => time(),
				'transaction_id' => $transaction_id,
			]);

			Db::commit();
			//发送外卖新订单提醒，管理员,店长
			$msg = make_new_order_msg($this);
			f_tpl_msg($msg,8,$this['wxapp_id'],$this['shop_id']);
			/*
			//发送模板消息 - 使用公众号
			if($this->user['union_id']){
				//判断是否关注公众号
				if($wxuser = UserModel::detail(['union_id' => $this->user['union_id'],'type' => 20])){
					//判断是否配置了模板消息
					$tmsg = SettingModel::getItem('tmsg',$wxuser['wxapp_id']);
					if($tmsg['payment']['template_id']){
						$tmsg['payment']['touser'] = $wxuser['open_id'];
						$tmsg['payment']['data']['keyword1']['value'] = $order['pay_price'].'元';
						$tmsg['payment']['data']['keyword2']['value'] = $order['order_no'];
						f_msg($tmsg['payment'],$wxuser['wxapp_id']); //发送模板消息
					}
				}	
			}
			*/	
			//获取打印机配置
			if($p_set = SettingModel::getItem('printer')){
				//如果开启打印机并且开启支付后打印 - 则执行打印小票
				if($p_set['is_open']==1 AND $p_set['pay_p']==1){
					$p = new PrinterModel;
					$p->gotoPrint($this,$p_set['p_n']);
				}
			}
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

}
